package com.example.service;

import org.springframework.stereotype.Service;

import com.example.constant.MessageConstant;
import com.example.constant.MessageDecoderConstant;
import com.example.constant.UCortrolConstant;
import com.example.entity.factory.Unpooled;
import com.example.entity.message.Message;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * 将接收到的二进制数据解码成信息
 * 
 * @author yao
 *
 */
@Service
public class MessageDecoder extends LengthFieldBasedFrameDecoder {

	/**
	 * 
	 * 
	 * @param maxFrameLength
	 * @param lengthFieldOffset
	 * @param lengthFieldLength
	 */
	public MessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment,
			int initialByteTostrip) {
		super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialByteTostrip);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("调用解析");
		ByteBuf frame = (ByteBuf) super.decode(ctx, in);
		if (frame == null) {
			return null;
		}
		Message message = null;
		// 丢弃
		int length = frame.getChar(1);
		if (frame.readByte() != MessageConstant.HEADER_START_SIGN
				|| frame.getByte(length + 2) != MessageConstant.BODY_END_TYPE) {
			System.out.println("丢弃");
			frame.release();
		} else {
			// 排除长度干扰
			frame.readChar();
			// 读取报文第4位作为开头的char变量，判断启动标识位
			if (frame.getChar(3) == MessageDecoderConstant.INIT_SIGN) {
				System.out.println("调用了init解码");
				message = Unpooled.wrapperInitMessage(frame);
			} else if (frame.readableBytes() == 5) {
				int uControlField = frame.readInt();
				if (uControlField == UCortrolConstant.U) {
					message = Unpooled.newUMessage4();
				}
			} else {
				System.out.println("其他报文 ");
				ByteBuf s = io.netty.buffer.Unpooled.copiedBuffer(frame);
				try {

					System.out.println("收到的报文拷贝:");
					System.out.println("     " + ByteBufUtil.hexDump(s));

					message = Unpooled.wrapper(frame);
				} catch (Exception e) {
					// TODO: handle exception
					System.out.println("报错报文拷贝");
					System.out.println(ByteBufUtil.hexDump(s));
					s.release();
					e.printStackTrace();
				}
			}
		}

		return message;
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		cause.printStackTrace();

	}

}
